package org.elanfox.cloud.mybatis.type;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.elanfox.cloud.common.enums.base.CodeDescCommonEnum;
import org.elanfox.cloud.common.enums.base.CodeDescEnumHelper;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/7/1
 */
@MappedTypes(CodeDescCommonEnum.class)
public class CodeDescEnumTypeHandler<E extends Enum<E> & CodeDescCommonEnum> extends BaseTypeHandler<E> {
    private final Class<E> type;

    public CodeDescEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, parameter.getCode());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object i = rs.getObject(columnName);

        if (rs.wasNull()) {
            return null;
        } else {
            try {
                return CodeDescEnumHelper.getEnumTypeByCode(type, i);
            } catch (Exception ex) {
                throw new IllegalArgumentException("Cannot convert " + i + " to " + "" + " by ordinal value.", ex);
            }
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object i = rs.getObject(columnIndex);

        if (rs.wasNull()) {
            return null;
        } else {
            try {
                return CodeDescEnumHelper.getEnumTypeByCode(type, i);
            } catch (Exception ex) {
                throw new IllegalArgumentException("Cannot convert " + i + " to " + "" + " by ordinal value.", ex);
            }
        }
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object i = cs.getObject(columnIndex);

        if (cs.wasNull()) {
            return null;
        } else {
            try {
                return CodeDescEnumHelper.getEnumTypeByCode(type, i);
            } catch (Exception ex) {
                throw new IllegalArgumentException("Cannot convert " + i + " to " + "" + " by ordinal value.", ex);
            }
        }
    }
}
